//
//  UserAccount.swift
//  SK微博
//
//  Created by 姜胜凯 on 15/10/11.
//  Copyright © 2015年 姜胜凯. All rights reserved.
//

import UIKit
//用户模型
class UserAccount: NSObject ,NSCoding{
    //用于调用access_token，接口获取授权后的access token
    var access_token: String?
    //access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //当前授权用户的UID。
    var uid: String?
    /// 过期日期
    var expiresDate: NSDate?
    init(dict :[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    override var description: String {
    
        let properties = ["access_token", "expires_in", "uid"]
        
       // return "\(dictionaryWithValuesForKeys(properties))"
    return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    
    
    //归档路径  1.保存用户账户时参数必须要用静态变量2.静态变量只需要加载一次，等在调用的时候不需要在加载了
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("account.plist")
//保存用户账户
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    
    
    }
    
    //MARK:解档  &  归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
//        aCoder.encodeObject(name, forKey: "name")
//        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
//        name = aDecoder.decodeObjectForKey("name") as? String
//        avatar_large = aDecode
    }
    
    
}
